
#include "Box2D/Box2D.h"
#include <SFML/System.hpp>
#include <SFML/Network.hpp>
#include <iostream>
#include <unistd.h>

#define LISTEN_PORT 4567

struct physicsWrapper
{
    b2World* gameWorld;
    sf::Mutex physicsMutex; 
};

void clientHandlerThread(void* userData){

    sf::TcpSocket* clientSocket = static_cast<sf::TcpSocket*>(userData);
    std::cout << "New client: " << clientSocket->getRemoteAddress() << std::endl;
  //  while(1)
  //  {
         // Receive a message from the client
         char buffer[1024];
         std::size_t received = 0;
         clientSocket->receive(buffer, sizeof(buffer), received);
         std::cout << "client said: " << buffer << std::endl;
/*
         // Send an answer
         std::string message = "Welcome, client";
         clientSocket.send(message.c_str(), message.size() + 1);
        sleep(1);
    }
*/
}

void listenerThread(void* userData)
{
    physicsWrapper* pw = static_cast<physicsWrapper*>(userData);

    //std::vector<sf::Thread> threadList;
    //std::vector<sf::TcpSocket> socketList;

    sf::TcpListener serverListener;
    std::cout << "Initializing listener" << std::endl;
    serverListener.listen(LISTEN_PORT);

    while(1) //TODO
    {

        std::cout << "Listening for client" << std::endl;
        sf::TcpSocket clientSocket;
        if(serverListener.accept(clientSocket) == sf::Socket::Done)
        {

            sf::Thread newThread(&clientHandlerThread, &clientSocket);
            newThread.launch();
            //socketList.push_back(clientSocket);
            //threadList.push_back(newThread);

        }
    }

    std::cout << "Bailing out\n";

}



int main()
{
    //
    // Box2D Stuff
    //
    b2Vec2 gravity = b2Vec2(0.0f,0.0f);
    b2World* gameWorld = new b2World(gravity);
    float32 timeStep = 1.0f / 30.f;
    int32 velocityIterations = 10;
    int32 positionIterations = 8;
    
    //Put the shared information into a struct
    physicsWrapper pw;
    pw.gameWorld = gameWorld;

    //Launch thread
    sf::Thread netThread(&listenerThread, &pw);
    netThread.launch();

    /*
    while(1){
        pw.physicsMutex.lock();
        gameWorld->Step(timeStep, velocityIterations, positionIterations);
        pw.physicsMutex.unlock();
    }*/
      return 0;
}



